<?php

class Synthesis_Workbench_MainController extends Mage_Core_Controller_Front_Action
{
	const MAX_FILE_SIZE = 5242880;
	/*
	 *	Preventing unwanted guest calls through URL
	*/
	
	public function _construct()
	{
		if(!Mage::helper('core')->isDevAllowed())
			die;
	}

    public function errorsAction()
    {
       $this->loadLayout();
	   $this->renderLayout();
	}
	
	/* CACHE ACTIONS */
	
    public function flushAllAction()
    {
        Mage::app()->getCacheInstance()->flush();
        echo Mage::helper('adminhtml')->__("The cache storage has been flushed.");
    }
	
    public function flushSystemAction()
    {
        Mage::app()->cleanCache();
        Mage::dispatchEvent('adminhtml_cache_flush_system');
        echo Mage::helper('adminhtml')->__("The Magento cache storage has been flushed.");
    }
	
    public function enableCacheAction()
    {
        $types = $this->getRequest()->getParam('types');
        $allTypes = Mage::app()->useCache();

        $updatedTypes = 0;
		
        foreach ($types as $code) {
            if (empty($allTypes[$code])) {
                $allTypes[$code] = 1;
                $updatedTypes++;
            }
        }
		
        if ($updatedTypes > 0) {
            Mage::app()->saveUseCache($allTypes);
            echo Mage::helper('adminhtml')->__("%s cache type(s) enabled.", $updatedTypes);
        }

    }
	
    public function disableCacheAction()
    {
        $types = $this->getRequest()->getParam('types');
        $allTypes = Mage::app()->useCache();

        $updatedTypes = 0;
		
        foreach ($types as $code) {
            if (!empty($allTypes[$code])) {
                $allTypes[$code] = 0;
                $updatedTypes++;
            }
            $tags = Mage::app()->getCacheInstance()->cleanType($code);
        }
		
        if ($updatedTypes > 0) {
            Mage::app()->saveUseCache($allTypes);
            echo Mage::helper('adminhtml')->__("%s cache type(s) disabled.", $updatedTypes);
        }

    }
	
    public function refreshCacheAction()
    {
        $types = $this->getRequest()->getParam('types');
        $updatedTypes = 0;
		
        if (!empty($types)) {
            foreach ($types as $type) {
                $tags = Mage::app()->getCacheInstance()->cleanType($type);
                Mage::dispatchEvent('adminhtml_cache_refresh_type', array('type' => $type));
                $updatedTypes++;
            }
        }
		
        if ($updatedTypes > 0) {
            echo Mage::helper('adminhtml')->__("%s cache type(s) refreshed.", $updatedTypes);
        }

    }
	
    /**
     * Clean JS/css files cache
     */
    public function cleanMediaAction()
    {
        try {
            Mage::getModel('core/design_package')->cleanMergedJsCss();
            Mage::dispatchEvent('clean_media_cache_after');
            echo Mage::helper('adminhtml')->__('The JavaScript/CSS cache has been cleaned.');

        }
        catch (Exception $e) {
            echo Mage::helper('adminhtml')->__('An error occurred while clearing the JavaScript/CSS cache.');
        }
        catch (Mage_Core_Exception $e) {
            echo $e->getMessage();
        }

    }
	
    /**
     * Clean JS/css files cache
     */
    public function cleanImagesAction()
    {
        try {
            Mage::getModel('catalog/product_image')->clearCache();
            Mage::dispatchEvent('clean_catalog_images_cache_after');
            $this->_getSession()->addSuccess(
                Mage::helper('adminhtml')->__('The image cache was cleaned.')
            );
        }
        catch (Mage_Core_Exception $e) {
            $this->_getSession()->addError($e->getMessage());
        }
        catch (Exception $e) {
            echo Mage::helper('adminhtml')->__('An error occurred while clearing the image cache.');

        }

    }
	
	public function cleanVarAction($dir = null)
	{
		Mage::helper('workbench')->deleteDirectory(Mage::helper('workbench')->getCachePath());
		echo $this->__('Cache directory cleaned out!');
	}
	
	/* REINDEXING */
    public function massReindexAction()
    {
		$index = $this->getRequest()->getParam('id');
        /* @var $indexer Mage_Index_Model_Indexer */
        $indexer    = Mage::getSingleton('index/indexer');

		if($index)
			$processIds = array($index);
		else
			$processIds = array(
						'catalog_product_attribute',
						'catalog_product_price', 
						'catalog_url', 
						'catalog_product_flat', 
						'catalog_category_flat', 
						'catalog_category_product', 
						'catalogsearch_fulltext', 
						'cataloginventory_stock', 
						'tag_summary'
						);
		
        if (empty($processIds) || !is_array($processIds)) {
           echo Mage::helper('index')->__('Please select Indexes');
        } else {
            try {
                foreach ($processIds as $processId) {
                    /* @var $process Mage_Index_Model_Process */
                    $process = $indexer->getProcessByCode($processId);
                    if ($process) {
                        $process->reindexEverything();
                    }
                }
                $count = count($processIds);
				if($count == 1)
					echo Mage::helper('index')->__('%s reindexed', $index);
				else
					echo Mage::helper('index')->__('Total of %d index(es) have reindexed data.', $count);
				
            } catch (Mage_Core_Exception $e) {
                echo $this->_getSession()->addError($e->getMessage());
            } catch (Exception $e) {
                echo Mage::helper('index')->__('Cannot initialize the indexer process.');
            }
        }

    }
	
	public function phpinfoAction()
	{
		ob_start () ;
		phpinfo () ;
		$pinfo = ob_get_contents () ;
		ob_end_clean () ;

		echo ( str_replace ( "module_Zend Optimizer", "module_Zend_Optimizer", preg_replace ( '%^.*<body>(.*)</body>.*$%ms', '$1', $pinfo ) ) ) ;
	}
	
	public function systemLogAction()
	{
        $file = Mage::getStoreConfig('dev/log/file');

		$logDir  = Mage::getBaseDir('var') . DS . 'log';
		$logFile = $logDir . DS . $file;
		
		if(file_exists($logFile))
			echo nl2br(file_get_contents($logFile));
		else
			echo $this->__('File does not exists!');		
	}
	
	public function executionTimeAction()
	{
		Mage::helper('workbench')->getExecutionTime($this->getRequest()->getParam('url'));
	}
	
	public function fileuploadAction()
	{
		$target_path = Mage::helper('workbench')->getDesignPath() . DS . $_FILES['file']['name'];

		$allowed_filetypes = array('.jpg','.gif','.bmp','.png');
		$filename = $_FILES['file']['name'];
		$ext = substr($filename, strpos($filename,'.'), strlen($filename)-1);
	 
		if(!in_array($ext, $allowed_filetypes)) {
			echo $this->__('The file you attempted to upload is not allowed.');
			die;
		}
	 
	    if(filesize($_FILES['file']['tmp_name']) > self::MAX_FILE_SIZE) {
			echo $this->__('The file you attempted to upload is too large.');
			die;
		}
		
		move_uploaded_file($_FILES['file']['tmp_name'], $target_path);
		echo $this->__('File was successfully uploaded!');
	}
	
	public function designAction()
	{
	
		$this->loadLayout();
		$this->renderLayout();
		
	}
	
	public function toggleHintsAction()
	{
		Mage::helper('workbench')->toggleConfig('dev', 'debug', 'template_hints');
		$this->_redirectReferer();
	}
	
	public function toggleTranslationAction()
	{
		Mage::helper('workbench')->toggleConfig('dev', 'translate_inline', 'active');
		$this->_redirectReferer();
	}
	
	public function toggleLoggingAction()
	{
		Mage::helper('workbench')->toggleConfig('dev', 'log', 'active');
		$this->_redirectReferer();
	}
	
}